import 'react-native-gesture-handler';
import * as React from 'react';
import { SafeAreaView, StyleSheet, StatusBar } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { useReduxDevToolsExtension } from '@react-navigation/devtools';
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import { Provider } from 'react-redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import AsyncStorage from '@react-native-community/async-storage';
import rootReducer from './src/redux/reducers';

import rootSaga from './src/sagas';
import Router from './src/routes';

import { AuthContext } from './src/components/context';
import { navigationRef, isReadyRef } from './src/routers/navigationRef';

function App() {
  const loginReducer = (prevState, action) => {
    switch (action.type) {
      case 'RESTORE_TOKEN':
        return {
          ...prevState,
          userToken: action.token,
          isLoading: false,
        };
      case 'SIGN_IN':
        return {
          ...prevState,
          isSignout: false,
          userToken: action.token,
        };
      case 'SIGN_OUT':
        return {
          ...prevState,
          isSignout: true,
          userToken: null,
        };
    }
  };

  const initialLoginState = {
    isLoading: true,
    isSignout: false,
    userToken: null,
  };

  const [state, dispatch] = React.useReducer(loginReducer, initialLoginState);

  React.useEffect(() => {
    const bootstrapAsync = async () => {
      let userToken;

      try {
        userToken = await AsyncStorage.getItem('userToken');
      } catch (e) {}

      dispatch({ type: 'RESTORE_TOKEN', token: userToken });
    };

    bootstrapAsync();
  }, []);

  React.useEffect(() => {
    return () => {
      isReadyRef.current = false;
    };
  }, []);

  const authContext = React.useMemo(
    () => ({
      signIn: async data => {
        dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
      },
      signOut: () => dispatch({ type: 'SIGN_OUT' }),
      signUp: async data => {
        dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
      },
    }),
    [],
  );

  // const navigationRef = React.useRef();

  // 创建一个saga中间件test
  const sagaMiddleware = createSagaMiddleware();

  // useReduxDevToolsExtension(navigationRef); 暂时先注释

  //创建store
  const store = createStore(
    rootReducer,
    composeWithDevTools(applyMiddleware(sagaMiddleware)),
  );

  //动态执行saga，注意：run函数只能在store创建好之后调用
  sagaMiddleware.run(rootSaga);

  console.log('next state', store.getState());
  console.log('state', state);

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="light-content" backgroundColor="#6a51ae" />
      <AuthContext.Provider value={authContext}>
        <Provider store={store}>
          <NavigationContainer
            ref={navigationRef}
            onReady={() => {
              isReadyRef.current = true;
            }}>
            <Router userToken={state.userToken} />
          </NavigationContainer>
        </Provider>
      </AuthContext.Provider>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});

export default App;
